package com.yycx.module.bus.provider.service.hy.impl;

import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.query.CriteriaUpdate;
import com.yycx.module.bus.client.entity.hy.BusPolicyCustom;
import com.yycx.module.bus.provider.mapper.hy.BusPolicyCustomMapper;
import com.yycx.module.bus.provider.service.hy.BusPolicyCustomService;
import com.yycx.common.mybatis.base.service.impl.BaseServiceImpl;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.module.system.client.entity.SysFormula;
import com.yycx.module.system.provider.service.SysFormulaService;
import org.springframework.stereotype.Service;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.mybatis.query.CriteriaQuery;
import org.springframework.transaction.annotation.Propagation;
import com.yycx.common.mybatis.query.CriteriaSave;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 政策详情接口实现类
 *
 * @author flyme
 * @date 2023-07-17
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusPolicyCustomServiceImpl extends BaseServiceImpl<BusPolicyCustomMapper, BusPolicyCustom> implements BusPolicyCustomService {

    @Resource
    private SysFormulaService sysFormulaService;

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, BusPolicyCustom bpc, EntityMap extra) {
        initBusBusPolicyCustom(bpc);
        return ResultBody.ok();
    }

    @Override
    public ResultBody beforeEdit(CriteriaUpdate<BusPolicyCustom> cu, BusPolicyCustom bps, EntityMap extra) {
        initBusBusPolicyCustom(bps);
        return super.beforeEdit(cu, bps, extra);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<BusPolicyCustom> cq, BusPolicyCustom bpc, EntityMap requestMap) {
        cq.orderByDesc("bpc.createTime");
        return ResultBody.ok();
    }


    /**
     * 设置公式内容字段
     *
     * @param bpc
     */
    private void initBusBusPolicyCustom(BusPolicyCustom bpc) {
        //市场结算公式ID
        Long settleFormulaId = bpc.getSettleFormulaId();
        if (FlymeUtils.isNotEmpty(settleFormulaId)) {
            SysFormula settleFormula = sysFormulaService.getById(settleFormulaId);
            bpc.setSettleFormula(settleFormula.getFormulaContent());
        }
    }

    /**
     * 根据商品ID和客户编号查询
     *
     * @param policyDrugId
     * @param customCode
     * @param sendDate
     * @return
     */
    public BusPolicyCustom findByPolicyDrugIdAndCustomCode(Long policyDrugId, String customCode, Date sendDate) {
        CriteriaQuery<BusPolicyCustom> cq = new CriteriaQuery(BusPolicyCustom.class);
        cq.eq(true, "policyDrugId", policyDrugId);
        cq.eq(true, "customCode", customCode);
        cq.le(true, "beginDate", sendDate);
        cq.and(e -> e.isNull("endDate").or().ge(true, "endDate", sendDate));
        return getOne(cq,false);
    }
}
